home *** CD-ROM | disk | FTP | other *** search
- Path: news1.erols.com!newsmaster@erols.com
- From: Chris Cobb <ccobb@erols.com>
- Newsgroups: comp.lang.c++
- Subject: Re: C++ keyword
- Date: 17 Mar 1996 00:45:31 GMT
- Organization: CSEG, Inc.
- Message-ID: <4ifnbb$amc@news7.erols.com>
- References: <mwoods-1403961501550001@ou048057.otago.ac.nz>
- NNTP-Posting-Host: ccobb.erols.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 1.22KIT (Windows; U; 16bit)
-
- mwoods@maths.otago.ac.nz (Matt B. Woods) wrote:
- >I am fairly new to C++ and I have just come across the keyword 'throw'.
- >As I cannot find a reference to this keyword I assume I must be reading
- >the wrong books. Can anyone tell me what 'throw' means? Even better
- >could someone recommend a good complete reference to the C++ language?
- >
-
- Throw is used to throw exceptions. Borland C++ 4.52 implements
- exceptions but many compilers do not yet implement them. The new
- Standard C++ Library will throw exceptions on error conditions so it will
- be prudent to understand how they work. An article in the Jan 96 issue
- of C++ Reports begins by describing how difficult they are to use, so
- this should be kept in mind. However, a *very* simple framework would
- be:
-
- even_numbers_only(int i)
- {
- if (i % 2)
- cout << i << " is even!" << endl;
- else
- {
- cerr << i << " is not even!" << endl;
- throw i;
- }
- }
-
- my_function()
- {
- try // try block: followed by one or more catch blocks
- {
- // call functions here that might throw exceptions
- even_numbers_only(3);
- }
- catch(...) // catch all exceptions
- {
- // some function in my try block threw an exception
- cerr << "Exception caught: some function in my try block "
- << "threw an exception!" << endl;
- cerr << "Error occured in my_function()." << endl;
- }
- }
-
- Throw and catching exceptions is not unlike using setjmp() and longjmp()
- in C. One important difference is that throwing an exception causes
- all objects on the call stack (including the try block) to be properly
- destruct-ed, which would not happen with longjmp.
-
- Chris Cobb
-
-
-